<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/11
 * Time: 19:02
 */

namespace App\CronTask;


use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\HttpClient\HttpClient;

class TeamCron extends AbstractCronTask
{
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        return '@monthly';
    }
    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        // 定时任务名称
        return 'team';
    }
    static function run(\swoole_server $server, int $taskId, int $fromWorkerId, $flags = null)
    {
        $tables = ['siam_kogteams','siam_dotateams','siam_csgoteams','siam_lolteams'];
        $path = [UrlEnums::KOG_TEAM_LISTS_PATH,UrlEnums::DOTA_TEAM_LISTS_PATH,UrlEnums::CSGO_TEAM_LISTS_PATH,UrlEnums::LOL_TEAM_LISTS_PATH];
        for ( $i=0;$i < count($path);$i++ ){
            $url = UrlEnums::FJURL.$path[$i].'?version=2&offset=0&limit=1000';
            $client = new HttpClient($url);
            list($s1, $s2) = explode(' ', microtime());
            $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
            $option = [
                'path'      => $path[$i],
                'api_time'  => $microtime
            ];
            $header = Auth::getInstance()->header($option);
            $client->setHeaders($header,true,false);
            $response = $client->get();
            $data = $response->getBody();
            $data = json_decode($data,true);
            $table = $tables[$i];
            if( isset($data['code']) && $data['code'] == 200 && $data['data'] ){
                MysqlPool::invoke(function (MysqlObject $db)use($data,$table){
                    foreach ( $data['data'] as $item ){
                        $team = $db->where('team_id',$item['team_id'])->getOne($table);
                        if( isset($item['player_ids']) ){
                            $item['player_ids'] = json_encode($item['player_ids']);
                        }
                        if( !$team ){
                            $res = $db->insert($table,$item);
                        }
                    }
                });
            }
        }
    }
}